import { state, sign } from './dapp'
import { useI18n } from './hooks/web/useI18n'
var token = ''
var login = false

function showErr(res) {
  if (res.code !== 200) {
    if (res.msg === '请先登录' || res.msg === 'err.noActive') {
      token = null
      login = false
      localStorage.setItem('token', '')
      localStorage.setItem('username', '')
    } else {
      const { t } = useI18n()
      Toast(t(res.msg))
    }
  }
}

async function get(url) {
  if (state.connectType === 'http') {
    if (url.indexOf('?') === -1) {
      url += '?'
    }
    url += `&token=${state.token}`
    var res = await fetch(url).then((res) => res.json())
    showErr(res)
    return res
  }
  if (!state.address) {
    return {}
  }
  if (url.indexOf('?') === -1) {
    url += '?'
  }
  url += `&address=${state.address}`
  var res = await fetch(url).then((res) => res.json())
  showErr(res)
  return res
}

async function post(url) {
  var signData = await sign()
  var res = await fetch(url + signData, { method: 'POST' }).then((res) =>
    res.json(),
  )
  showErr(res)
  return res
}

export default {
  get,
  post,
}
